import TableContainer from "@/components/TableContainer"
import useTableSelector from "@/components/useTableSelector"
import { PAGINATION_CONFIG } from "@/constants"
import { OrderState, PayType } from "@/constants/enums/goods"
import { queyGoodsOrderList, deliverGoodsOrder } from "@/services/goods"
import { useRequest } from "ahooks"
import { Button, Checkbox, Col, DatePicker, Form, Input, Modal, Popconfirm, Row, Select, Space, Table, Tabs, message } from "antd"
import { ColumnsType } from "antd/es/table"
import { useMemo, useState } from "react"
import { history, Access } from '@umijs/max'
import dayjs from "dayjs"
import TableActions from "@/components/TableActions"
import { jump2target } from "@/utils/common"

const expressCompanyList = [
  {label: '跨越速运', value: 'KYEXPRESS'},
  {label: '顺丰', value: 'SFEXPRESS'},
  {label: '中通', value: 'ZTO'},
  {label: '壹米滴答', value: 'YIMIDIDA'},
]

const GoodsOrder: React.FC<RoutePageProps> = () => {
  const [searchForm] = Form.useForm()
  const [searchParams, setSearchParams] = useState<Goods.QueryGoodsOrderParams>({
    pageNum: 1, pageSize: 10, type: 'Mall',
  });
  const [checkAllLeftPadding, setCheckAllLeftPadding] = useState(8)
  const orderList = useRequest(() => queyGoodsOrderList(searchParams), {
    refreshDeps: [searchParams],
    onSuccess: () => {
      setTimeout(() => {
        const selectionDom = document.querySelector('.ant-table-selection-column')
        if (selectionDom) {
          setCheckAllLeftPadding((selectionDom.clientWidth - 16) / 2)
        }
      }, 10)
    }
  })
  const { getSelected, setSelected, effect } = useTableSelector()
  const [tabKey, setTabKey] = useState('all')
  const deliverReq = useRequest(deliverGoodsOrder, {manual: true})

  const onFinish = (values: any) => {
    setSearchParams({
      ...searchParams,
      orderCode: values.orderCode,
      nickName: values.nickName,
      recipient: values.recipient,
      phone: values.phone,
      payType: values.payType,
      startTime: values.timeType === 'createTime' ? values.timeRange?.[0]?.valueOf() : undefined,
      endTime: values.timeType === 'createTime' ? values.timeRange?.[1]?.valueOf() : undefined,
      payStartTime: values.timeType === 'payTime' ? values.timeRange?.[0]?.valueOf() : undefined,
      payEndTime: values.timeType === 'payTime' ? values.timeRange?.[1]?.valueOf() : undefined,
      deliverStartTime: values.timeType === 'deliverTime' ? values.timeRange?.[0]?.valueOf() : undefined,
      deliverEndTime: values.timeType === 'deliverTime' ? values.timeRange?.[1]?.valueOf() : undefined,
      takeStartTime: values.timeType === 'receiptTime' ? values.timeRange?.[0]?.valueOf() : undefined,
      takeEndTime: values.timeType === 'receiptTime' ? values.timeRange?.[1]?.valueOf() : undefined,
      pageNum: 1,
    })
  }
  const jump2detail = (id?: string) => {
    jump2target(`/order/mall/physical/detail?id=${id || ''}`, {needRefresh: true})
  }
  const onTabKeyChange = (key: OrderState | 'all') => {
    setTabKey(key)
    setSearchParams({
      ...searchParams,
      orderState: key === 'all' ? undefined : key,
      pageNum: 1,
    })
  }
  const deliverGoods = async (record: Goods.Order) => {
    let companyCode = ''
    let logistics = ''
    Modal.confirm({
      title: '快递单号',
      content: <div>
        <Select placeholder='快递公司' style={{width: '100%', marginBottom:16}} options={expressCompanyList} onChange={value => companyCode = value} />
        <Input placeholder="快递单号" onChange={({target}) => logistics = target.value} />
      </div>,
      onOk: async () => {
        logistics = logistics.trim()
        if (!companyCode) {
          message.error('请选择快递公司')
          return Promise.reject()
        }
        if (!logistics) {
          message.error('请输入有效的快递单号')
          return Promise.reject()
        }
        return deliverReq.runAsync({
          orderId: record.orderId,
          companyCode,
          logistics,
        }).then(orderList.refresh)
      }
    })
  }

  const columns: ColumnsType<Goods.Order> = [
    {
      title: '订单号',
      dataIndex: 'orderCode',
      width: 120,
      render: val => {
        return <div className="w-[88px] text-wrap">{val}</div>
      }
    },
    {
      title: '商品信息',
      dataIndex: 'content',
      width: 350,
      render: (_, record) => {
        return record.content.map((item, index) => {
          console.log(item)
          item._contentInfo = JSON.parse(item.contentInfo)
          item._contentInfo._goodsShow = JSON.parse(item._contentInfo.goodsShow)
          item._contentReceivable = JSON.parse(item.contentReceivable)
          const _price = item._contentReceivable.find(it => it.type === 'Cost')
          return <div key={index} className={`w-80 flex ${index ? 'border-t' : ''}`} style={{borderColor: 'var(--ant-color-split)'}}>
            <img className="w-14 h-14 mr-2 shrink-0" src={item._contentInfo._goodsShow[0].source} />
            <div className="grow">
              <div>{item._contentInfo.goodsName}</div>
              <div>{item._contentInfo.stockName}</div>
            </div>
            <div className="shrink-0 ml-2 text-right">
              <div>¥ {_price.amount}</div>
              <div>{item.num} 件</div>
            </div>
          </div>
        })
      }
    },
    {
      title: '费用信息(元)',
      width: 200,
      dataIndex: 'amount',
      render: (_, record) => {
        if (record.payInfo) {
          record._payInfo = JSON.parse(record.payInfo)
        }
        record._deduction = JSON.parse(record.deduction)
        const _price = record._deduction.reduce((init, item) => {
          if (item.type === 'Cost') {
            init.goods += item.num
          } else if (item.type === 'Coupon') {
            init.coupon += item.num
          } else if (item.type === 'Logistics') {
            init.logistics += item.num
          }
          return init
        }, {goods: 0, coupon: 0, logistics: 0})
        return <div>
          <div>商品总价：{_price.goods.toFixed(2)}</div>
          <div>快递费用：{_price.logistics.toFixed(2)}</div>
          <Access accessible={!!_price.coupon}>
            <div>优惠减免：-{_price.coupon.toFixed(2)}</div>
          </Access>
          <div>应收金额：{record.amount}</div>
          <div>实收金额：{record._payInfo?.amount || '--'}</div>
        </div>
      }
    },
    {
      title: '买家/收货人',
      dataIndex: 'creator',
      width: 160,
      render: (_, record) => {
        return <div>
          <div>买家：{record.nickName}</div>
          <div>收货人：{record.recipient} {record.phone}</div>
        </div>
      }
    },
    {
      title: '付款方式',
      dataIndex: 'creator',
      width: 120,
      render: (_, record) => {
        switch (record.payType) {
          case PayType.余额: return '余额支付'
          case PayType.微信支付: return '微信支付'
          default: return '--'
        }
      }
    },
    {
      title: '订单状态',
      dataIndex: 'orderState',
      render: (_, record) => {
        switch (record.orderState) {
          case OrderState.待支付: return '等待买家付款'
          case OrderState.支付成功: return '等待卖家发货'
          case OrderState.发货: return '等待买家收货'
          case OrderState.收货: return '买家已收货'
          case OrderState.取消: return '订单已取消'
          case OrderState.售后中: return '售后中，等待卖家处理'
          case OrderState.退款: return '卖家已退款'
          default: return '--'
        }
      }
    },
    {
      title: '下单时间',
      dataIndex: 'createTime',
      render: val => val ? dayjs(val).format('YYYY-MM-DD HH:mm:ss') : '--',
    },
    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 120,
      render: (_, record) => {
        return (
          <TableActions>
            <a onClick={() => jump2detail(record.orderId)}>详情</a>
            <Access accessible={record.orderState === OrderState.支付成功}>
              <a onClick={() => deliverGoods(record)}>发货</a>
            </Access>
          </TableActions>
        )
      }
    },
  ]

  const onCheckAllChange = (checked: boolean) => {
    setSelected(searchParams.pageNum, checked ? (orderList.data?.data || []).map(item => item.orderId) : [])
  }

  const checkAll = useMemo(() => {
    let currentTotal = orderList.data?.data?.length || 0
    let currentSelectedTotal = getSelected(searchParams.pageNum).length
    return {
      checked: currentSelectedTotal === currentTotal,
      indeterminate: currentSelectedTotal > 0 && currentSelectedTotal < currentTotal
    }
  }, [orderList.data, effect, searchParams])

  return (
    <TableContainer>
      <TableContainer.SearchContainer>
        <Form colon={false} name='searchStationListForm' form={searchForm} onFinish={onFinish} initialValues={{timeType: 'createTime'}}>
          <Row gutter={[20, 20]}>
            <Col span={6}>
              <Form.Item label='订单号' name='orderCode'>
                <Input placeholder="请输入" variant="borderless" />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label='买家昵称' name='nickName'>
                <Input placeholder="请输入" variant="borderless" />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label='收货人' name='recipient'>
                <Input placeholder="请输入" variant="borderless" />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label='收货人手机号' name='phone'>
                <Input placeholder="请输入" variant="borderless" />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label='付款方式' name='payType'>
                <Select
                  placeholder='请选择'
                  allowClear
                  variant="borderless"
                  options={[
                    {label: '余额支付', value: PayType.余额},
                    {label: '微信支付', value: PayType.微信支付},
                  ]}
                />
              </Form.Item>
            </Col>
            <Col flex={'500px'}>
              <Form.Item label={
                <Form.Item name='timeType' noStyle>
                  <Select
                    options={[
                      {label: '下单时间', value: 'createTime'},
                      {label: '付款时间', value: 'payTime'},
                      {label: '发货时间', value: 'deliverTime'},
                      {label: '收货时间', value: 'receiptTime'},
                    ]}
                    variant='borderless'
                    size="small"
                  />
                </Form.Item>
              } colon={false}>
                <Form.Item name='timeRange' noStyle>
                  <DatePicker.RangePicker showTime variant="borderless" />
                </Form.Item>
              </Form.Item>
            </Col>
            <Col span={24}>
              <Space>
                <Button type='primary' htmlType='submit' loading={orderList.loading}>筛选</Button>
                <Button htmlType='reset'>重置</Button>
              </Space>
            </Col>
          </Row>
        </Form>
      </TableContainer.SearchContainer>
      <Tabs
        items={[
          {label: '全部', key: 'all'},
          {label: '待付款', key: OrderState.待支付},
          {label: '待发货', key: OrderState.支付成功},
          {label: '已发货', key: OrderState.发货},
          // {label: '售后中', key: OrderState.售后中},
          {label: '已完成', key: OrderState.收货},
          {label: '已取消', key: OrderState.取消},
        ]}
        activeKey={tabKey}
        onChange={val => onTabKeyChange(val as any)}
        tabBarExtraContent={{
          left: <div style={{padding: 8}}></div>
        }}
      />
      <Table<Goods.Order>
        rowKey='orderId'
        loading={orderList.loading}
        dataSource={orderList.data?.data}
        columns={columns}
        scroll={{y: 700, x: 'max-content'}}
        // rowSelection={{
        //   selectedRowKeys: getSelected(searchParams.pageNum),
        //   onChange: (rowKeys) => setSelected(searchParams.pageNum, rowKeys),
        // }}
        pagination={{
          ...PAGINATION_CONFIG,
          current: searchParams.pageNum,
          pageSize: searchParams.pageSize,
          total: orderList.data?.totalCount || 0,
          onChange: (page, pageSize) => {
            setSearchParams({
              ...searchParams,
              pageNum: page === searchParams.pageNum ? 1 : page,
              pageSize,
            })
          },
          // position: ['bottomRight', 'topLeft'],
          showTotal: total => [
            // <Space key='selection' style={{paddingLeft: checkAllLeftPadding}}>
            //   <Checkbox
            //     checked={checkAll.checked}
            //     indeterminate={checkAll.indeterminate}
            //     onChange={({target}) => onCheckAllChange(target.checked)}
            //   >当页全选</Checkbox>
            //   {/* <Button onClick={openPriceDrawer}>设置电价</Button> */}
            // </Space>,
            <div key='total' className="ml-auto">{`共${total}条`}</div>,
          ],
        }}
      />
    </TableContainer>
  )
}

export default GoodsOrder
